package com.gxa.servlet.getmoney;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.pojo.Result;
import com.gxa.pojo.goods.Goods;
import com.gxa.service.upgoodsservice.UpGoodsService;
import com.gxa.service.upgoodsservice.upGoodsServiceImpl.UpGoodsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/UpGoodsServlet2")
public class UpGoodsServlet2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/json;charset=UTF-8");

        //1.获取前端请求
        //因为request.getreader（）方法只能读一次，采用下面几行代码
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
        StringBuilder json = new StringBuilder();
        String inputStr;
        while ((inputStr = streamReader.readLine()) != null) {
            json.append(inputStr);
        }
        //1.1这是将json转化为字符串的形式
        String jsonString = json.toString();
        //2.将json字符串转化为对象
        ObjectMapper objectMapper = new ObjectMapper();
        Goods goods = objectMapper.readValue(jsonString, Goods.class);
        //获取商品名称和数量
        String barcode = goods.getBarcode();
       int count = goods.getCount();
        System.out.println(count);

        //根据条形码查名字和单价
        UpGoodsService upGoodsService = new UpGoodsServiceImpl();
        //获取单位
        String danWei = upGoodsService.findDanWei(barcode);
        //获取名字
        String name = upGoodsService.findName(barcode);
        //设置
        goods.setGname(name);
        goods.setUnit(danWei);
        Boolean aBoolean = upGoodsService.addGoods(barcode, count);
        System.out.println(aBoolean);

        //返回处理
        PrintWriter writer = response.getWriter();
        Map<String,Object> map = new HashMap<>();
        String a = null;
        if(goods !=null){
            map.put("result", Result.ok("success",goods));
            a= objectMapper.writeValueAsString(map);
        }else {
            map.put("result",Result.error());
            a = objectMapper.writeValueAsString(map);
        }

        //返回
        writer.write(a);
        writer.flush();
        writer.close();
        streamReader.close();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
